/*
 * Copyright (c) 2009 - 2015, Aven's Lab. All rights reserved.
 *                   http://www.ocrking.com
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *  $Id: OcrKing.java,v 0.1 2014/10/29 23:50:18 $
 * The Java script for OcrKing Api
 * By Aven <Aven@OcrKing.Com>
 * Welcome to follow us 
 * http://weibo.com/OcrKing
 * http://t.qq.com/OcrKing
 * Warning! 
 * Before running this script , you should modify some parameter
 * within the post data according to what you wanna do
 */
package testGroovy;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

class TestORCKING {

	// the url below can not be changed !!
	private static final APIURL = 'http://39.65.100.4:6080/ok.html'
	// replace the word KEY below with your apiKey obtained by Email
	private static final APIKEY = '15e93936911230b309Iqy1IkcUx0TRctVhhjBh8ubfsH7fTixOZ01wkhUDeJ0pyoepK5J8j2ubcyasbzqn'
	private static final TYPE = 'http://www.pingan.com/ebusiness/auto/newness/index.do?cityCode=110100&provinceCode=110000'
	private static final FILEPATH="C:\\Users\\houjinxin\\Desktop\\code\\5.gif"
	
	static main(args) {
		10.times {
			println it
			run(FILEPATH)
		}
	}
	
	def static run(filePath) {
		def dataMap = [
			service: 'OcrKingForCaptcha',
			language: 'eng',
			charset: '7',
			type: TYPE,
			apiKey:APIKEY
		]
		def fileMap = [
			ocrfile : filePath
		]
		println postMultipart(APIURL, dataMap, fileMap)
	}

	/**
	 * post data with file uploading
	 * @param urlStr  the address to upload
	 * @param dataMap post data
	 * @param fileMap file to upload
	 * @return xml result
	 */
	def static postMultipart(apiUrl, dataMap, fileMap) {
		def res = '';
		def boundary = '----------------------------OcrKing_Client_Aven_s_Lab'
		def proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress('localhost', 8888))
		HttpURLConnection conn = null
		try {
			conn = (HttpURLConnection)(new URL(apiUrl)).openConnection(proxy).with { it ->
				it.connectTimeout = 5000
				it.readTimeout = 30000
				it.doOutput = true
				it.doInput = true
				it.useCaches = false
				it
			}
			conn.requestMethod = 'POST'
			conn.setRequestProperty 'Connection', 'Keep-Alive'
			conn.setRequestProperty 'Referer', 'http://lab.ocrking.com/?javaclient0.1)'
			conn.setRequestProperty 'User-Agent', 'Mozilla/5.0 (Windows NT 5.1; zh-CN; rv:1.9.1.3) Gecko/20100101 Firefox/8.0'
			conn.setRequestProperty 'Content-Type', "multipart/form-data; boundary=${boundary}"
			def out = new DataOutputStream(conn.getOutputStream());
			// data
			if (dataMap != null) {
				def strBuf = dataMap.collect { entry -> 
					"\r\n--${boundary}\r\nContent-Disposition: form-data; name=\"${entry.key}\"\r\n\r\n${entry.value}" 
				}.inject { prev, curr ->
					prev + curr
				}
				out.write(strBuf.toString().bytes);
			}

			// file
			if (fileMap != null) {
				fileMap.each { entry ->
					def file = (entry.value) as File
					def sbf =  "\r\n--${boundary}\r\nContent-Disposition: form-data; name=\"${entry.key}\"; filename=\"${file.name}\"\r\nContent-Type:application/octet-stream\r\n\r\n" 
					out.write(sbf.toString().getBytes())
					def ins = new DataInputStream(new FileInputStream(file))  
					int bytes = 0 
					byte[] bufferOut = new byte[1024]
					while ((bytes = ins.read(bufferOut)) != -1) {
						out.write(bufferOut, 0, bytes)
					}
					ins.close()
				}
			}

			byte[] endData = "\r\n--${boundary}--\r\n".getBytes()
			out.write(endData);
			out.flush();
			out.close();

			// handle the response
			StringBuffer strBuf = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuf.append(line).append("\n");
			}
			res = strBuf.toString();
			reader.close();
			reader = null;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
		res
	}

}